function HandleDialogIPayment(gui, item, options) {
  this._gui = gui;
  this._item = item;
  this._options = options;
  this._popupBox2 = new PopupBox2();
  this._operator = (options && options.operator) ? options.operator : null;
  this._now = (options && options.now) ? options.now : null;
  this._popupBox = (options && options.pop) ? options.pop : null;
  this._createElements();
};

HandleDialogIPayment.prototype._createElements = function() {
  this._loadData();
};

HandleDialogIPayment.prototype._loadData = function() {
  this._customer = null;
  this._retrieveCustomer();
};

HandleDialogIPayment.prototype._verifyData = function() {
  if (this._customer) {
    this._updateElements();
  }
};

HandleDialogIPayment.prototype._retrieveCustomer = function() {
  var _self = this;
  /*new RequestUtils()._read('customer', null, 'd.oid=' + this._item, null, null, null, null, function(result, params) { _self._customer = (result.data.length == 1) ? result.data[0] : null;
                                                                                                                       if (_self._customer == null) {
                                                                                                                         window.alert('No Customer. ' + _self._item);
                                                                                                                         _self._popupBox._close();
                                                                                                                       }
                                                                                                                       _self._verifyData.call(_self);
                                                                                                                     }, null);
*/

   var args = '&oid=' + this._item; 
  new RequestUtils()._mysql('v1customer', args, function(result, params) { _self._customer = (result.data.length == 1) ? result.data[0] : null;
                                                                         if (_self._customer == null) {
                                                                           window.alert('No Customer. ' + _self._item);
                                                                           _self._popupBox._close();
                                                                         }
                                                                          _self._verifyData.call(_self);
                                                                        }, {php:'customphp/mysqlread.php'});  
};

HandleDialogIPayment.prototype._updateElements = function() {
  var table, tr, td, radio, input, _self = this;
  DOMUtils.removeChildElements(this._gui.customNo);

  /* 初始化页面的OrderTrackId */
  MiscUtils.sort(this._customer.orders, ['id']);
  this._orderTrackId = (this._orderTrackId) ? this._orderTrackId : this._customer.orders[0].trackId;
  
  this._gui.customNo.appendChild(document.createTextNode('Customer ' + DlmanageUtils.customerId(this._item)));
  
  this._updateOrders();
};

HandleDialogIPayment.prototype._updateOrders = function() {
  var _self = this;
  DOMUtils.removeChildElements(this._gui.orderTab);
  DOMUtils.removeChildElements(this._gui.payment.price);
  DOMUtils.removeChildElements(this._gui.payment.received);
  DOMUtils.removeChildElements(this._gui.payment.anticipated);
  
  /* 显示订单的标签 */
  var func = function(trackId) { _self._orderTrackId = trackId; 
                                 _self._updateOrders.call(_self);
                               };
  new IContainerTabOrders(this._gui.orderTab, this._customer.orders, { callbackFunc: func, trackId: this._orderTrackId });
  
  /* 处理订单 */
  this._updateOrder();
};

HandleDialogIPayment.prototype._updateOrder = function() {
  var table, tr, td, order = DlmanageUtils.order(this._customer.orders, this._orderTrackId), _self = this;

  /* 设置Payment版块*/
  var total = 0;
  for (var i = 0, il = order.payments.length; i < il; i++) {
    var p = order.payments[i];
    if (p.cancelled == 1) {
      continue;
    }
    total += parseFloat(p.amount, 10);
  }
  
  this._gui.payment.price.appendChild(document.createTextNode('$' + order.price));
  this._gui.payment.price.appendChild(document.createTextNode(((order.price) > 0) ? ' (Inc. ' + '{{$smarty.const.TAX|escape:javascript}}' + '$' + (order.price * parseFloat(1 + parseFloat('{{$smarty.const.GST|escape:javascript}}'), 10)).toFixed(2) + ')' : ''));

  this._gui.payment.received.appendChild(document.createTextNode('$' + total.toFixed(2)));
  this._gui.payment.anticipated.appendChild(document.createTextNode('$' + ((order.price * parseFloat(1 + parseFloat('{{$smarty.const.GST|escape:javascript}}'), 10)) - total).toFixed(2)));

  this._paymentDate = this._now;
  
  var rules = DlmanageUtils.payment(order.type);
  if (rules[0]) {
    this._gui.payment.pay1.container.style.display = 'block';
    this._pay(this._gui.payment.pay1, 1, rules[0]);
  } else {
    this._gui.payment.pay1.container.style.display = 'none';
  }
  if (rules[1]) {
    this._gui.payment.pay2.container.style.display = 'block';
    this._pay(this._gui.payment.pay2, 2, rules[1]);
  } else {
    this._gui.payment.pay2.container.style.display = 'none';
  }
  if (rules[2]) {
    this._gui.payment.pay3.container.style.display = 'block';
    this._pay(this._gui.payment.pay3, 3, rules[2]);
  }
   else {
    this._gui.payment.pay3.container.style.display = 'none';
  }
  if (rules[3]) {
    this._gui.payment.pay4.container.style.display = 'block';
    this._pay(this._gui.payment.pay4, 4, rules[3]);
  } else {
    this._gui.payment.pay4.container.style.display = 'none';
  }
};

HandleDialogIPayment.prototype._pay = function(gui, stage, rule) {
  var table, tr, td, a, order = DlmanageUtils.order(this._customer.orders, this._orderTrackId), _self = this;
  
  DOMUtils.removeChildElements(gui.paid);
  DOMUtils.removeChildElements(gui.due);
  DOMUtils.removeChildElements(gui.history);
  DOMUtils.removeChildElements(gui.percent);
  
  
  var payment = Payment.instance();
  payment.stage = stage;
  payment.method = '';
  payment.orderFlag = order.flag;
  payment.customerId = this._customer.id;
  
  gui.container.style.verticalAlign = 'top';
  gui.percent.appendChild(document.createTextNode(rule.title));
  gui.fee.value = '';
  
  gui.cash.checked = false;
  gui.cheque.checked = false;
  gui.bank.checked = false;
  
  gui.cash.onclick = function() { payment.method = 'cash'; };
  gui.cheque.onclick = function() { payment.method = 'cheque'; };
  gui.bank.onclick = function() { payment.method = 'bank transfer'; };
  
  gui.payBtn.onclick = function() { if (gui.fee.value == '' || gui.fee.value == 0) {
                                      window.alert('数值不能为\'' + gui.fee.value + '\'');
                                      return;
                                    } 
                                    if (payment.method == '') {
                                      window.alert('必须选择支付方式');
                                      return;
                                    }
                                    if (!_self._paymentDate) {
                                      window.alert('必须选择支付日期');
                                      return;
                                    }
                                    if (payment.method != 'cash') {
                                      payment.status = 1;
                                    }
                                    payment.date = _self._paymentDate;
                                    payment.amount = gui.fee.value;
                                    payment.userAccount = _self._operator.account;
                                    order.payments[order.payments.length] = payment;
                                    new RequestUtils()._mwrite('paymentadd', [order], [], function() { _self._retrieveCustomer.call(_self); }, { pos: DOMUtils.findPos(this) });
                                  };
  
  table = document.createElement('table');
  table.cellPadding = 0;
  table.cellSpacing = 0;
  gui.history.appendChild(table);
  var total = 0;
  for (var i = 0, il = order.payments.length; i < il; i++) {
    var p = order.payments[i];
    if (p.stage != stage) {
      continue;
    }
    if (p.cancelled == 0) {
      total += parseFloat(p.amount, 10);
    }
    
    tr = table.insertRow(-1);
    td = tr.insertCell(-1);
    td.style.height = '12px';
    if (p.cancelled == 1) {
      td.style.textDecoration = 'line-through';
    }
    var method = '';
    if (p.method == 'cash') {
      method = 'c';
    } else if (p.method == 'cheque') {
      method = 'q';
    } else if (p.method == 'bank transfer') {
      method = 'b';
    }
    td.appendChild(document.createTextNode('Paid: (' + method.toUpperCase() + ')'));
    
    td = tr.insertCell(-1);
    td.style.padding = '0 0 0 1px';
    if (p.cancelled == 1) {
      td.style.textDecoration = 'line-through';
    }
    td.appendChild(document.createTextNode('$' + p.amount));

    td = tr.insertCell(-1);
    td.style.padding = '0 0 0 3px';
    if (p.cancelled == 1) {
      td.style.textDecoration = 'line-through';
    }
    td.appendChild(document.createTextNode('Date: ' + SimpleDate.format(p.date)));
    
    td = tr.insertCell(-1);
    td.style.padding = '0 0 0 3px';
    if (p.cancelled == 1) {
      td.style.textDecoration = 'line-through';
    }
    td.appendChild(document.createTextNode(p.userAccount));
    
    td = tr.insertCell(-1);
    td.style.padding = '0 0 0 3px';
    if (p.cancelled == 0) {
      a = document.createElement('img');
      a.src = 'images/common/delete.png';
      a.style.cursor = 'pointer';
      a._payment = p;
      a.onclick = function() { var pos = DOMUtils.findPos(this);
                               var div = document.createElement('div');
                               var payment = this._payment
                               var func1 = function() { payment.cancelled = 1;
                                                        payment.cancelledDate = _self._now;
                                                        payment.cancelledOperator = _self._operator.account;
                                                        payment.cancelledMessage = payment._text;
                                                        new RequestUtils()._mwrite('v1payment_c', [payment], [], function() { _self._retrieveCustomer.call(_self); }, { pos: pos });
                                                        _self._popupBox2._close();
                                                      };
                               var func2 = function() { _self._popupBox2._close(); };
                               MiscUtils.dialog(_self._popupBox2, pos, div, func1, func2, {t: 'Cancel Reason'});
                               new DialogInput(div, payment, { title: '' });
                               return false;
                             };
      td.appendChild(a);
    } else {
      td.style.color = '#ff0000';
      if (p.cancelledMessage.length > 0) {
        td.appendChild(document.createTextNode((p.cancelledMessage.length > 8) ? p.cancelledMessage.substring(0, 8) + '...' : p.cancelledMessage));
        var a = document.createElement('a');
        a.href = '#';
        a.appendChild(document.createTextNode('All'));
        a._payment = p;
        a.onclick = function() { func1 = function() { _self._popupBox2._close(); };
                                 var pos = DOMUtils.findPos(this);
                                 var div = document.createElement('div');
                                 div.style.verticalAlign = 'top';
                                 div.style.width = '420px';
                                 div.style.color = '#ff0000';
                                 div.style.textAlign = 'left';
                                 div.style.padding = '4px 0 0 10px';
                                 div.style.wordWrap = 'break-word';
                                 div.appendChild(MiscUtils.span('\n' + this._payment.cancelledMessage));
                                 MiscUtils.dialog(_self._popupBox2, pos, div, func1, null, {t: 'Cancel Reason (' + this._payment.cancelledOperator + ', ' + SimpleDate.format(this._payment.cancelledDate) + ')', width: 460, height: 100});
                                 return false;
                               };
        td.appendChild(a);
      } else {
        td.appendChild(document.createTextNode('(none)'));
      }
    }
  }
  
  var received = 0;
  for (var i = 0, il = order.payments.length; i < il; i++) {
    var p = order.payments[i];
    if (p.cancelled == 1) {
      continue;
    }
    received += parseFloat(p.amount, 10);
  }
  if (total.toFixed(2) > 0) {
    gui.paidc.style.color = '#0066ff';
    gui.paid.style.color = '#0066ff';
  } else {
    gui.paidc.style.color = '#000000';
    gui.paid.style.color = '#000000';
  }
  gui.paid.appendChild(document.createTextNode('$' + total.toFixed(2)));
  gui.due.appendChild(document.createTextNode('$' + ((((order.price * rule.rate * parseFloat(1 + parseFloat('{{$smarty.const.GST|escape:javascript}}'), 10)) - received).toFixed(2) > 0) ? ((order.price * rule.rate * parseFloat(1 + parseFloat('{{$smarty.const.GST|escape:javascript}}'), 10)) - received).toFixed(2) + ' (Inc. ' + '{{$smarty.const.TAX|escape:javascript}}' + ')' : '0.00')));
};
